package com.itbaizhan.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

//敏感词拦截器   与MyController2相关
public class SensitiveWordInterceptor implements HandlerInterceptor {
   ////请求到达controller前执行   改为true 让它通行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
    //跳转到JSP页面前执行，此时可以向request域添加数据
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //定义敏感词
        String[] sensitiveWords = {"笨蛋","暴力"};
        //获取Model中的所有数据 （控制器中的数据）
        Map<String, Object> model = modelAndView.getModel();
        //model的键值对
        Set<Map.Entry<String, Object>> entries = model.entrySet();
        //遍历model中的数据，替换敏感词
        for (Map.Entry<String,Object> entry:entries){
            String key = entry.getKey();
            String value = entry.getValue().toString();
            //将model值和敏感词列表遍历比对
            for(String sensitiveWord:sensitiveWords){
                // 如果model值包含敏感词，则替换
                if(value.contains(sensitiveWord)) {
                    String newStr = value.replaceAll(sensitiveWord, "***");
                    //放回前端页面
                    model.put(key, newStr);
                }
            }
        }
    }
}
